// 工作台
import React from 'react';
import { observer, useLocalStore } from 'mobx-react-lite';
import { Link } from 'react-router-dom';
import { Card, Avatar, Divider } from 'antd';
import moment from 'moment';
import {
  RightOutlined,
  FormOutlined,
  EyeOutlined,
  MessageOutlined,
} from '@ant-design/icons';
import * as projectApi from '~/apis/project/listApi';
import * as dashboardApi from '~/apis/dashboard/dashboardApi';
import * as experienceApi from '~/apis/experience/experienceApi';
import * as policyApi from '~/apis/policy/listApi';
import { config } from '~/config/config';
import { ProjectDistribution } from './ProjectDistribution';
import { InstitutionDistribution } from './InstitutionDistribution';
import { ViewMessageModal } from './ViewMessageModal';
import { ReplyMessageModal } from './ReplyMessageModal';
import './index.local.sass';

const cardConfig = {
  size: 'small' as const,
  bordered: false,
};

const setCardTitle = (title: string) => (
  <div className="card-title">
    <span className="title-icon">&nbsp;</span>
    <span>{title}</span>
  </div>
);

const setCardExtra = (text: string, href: string) => (
  <Link to={href} className="title-link link">
    {text}
    <RightOutlined className="link-icon" />
  </Link>);

const DashboardPage = observer(() => {
  const state = useLocalStore(() => ({
    currentInfo: {} as any,
    projectList: [] as Array<any>,
    messagesList: [] as Array<any>,
    navList: [] as Array<any>,
    interestedProjectList: [] as Array<any>,
    caseList: [] as Array<any>,
    experienceList: [] as Array<any>,
    policyList: [] as Array<any>,
    viewMessageModal: {
      visible: false,
      rowData: {} as any,
    },
    replyMessageModal: {
      visible: false,
      rowData: {} as any,
    },
  }));

  // 工作台 - 获取用户信息
  const getCurrentInfo = async () => {
    await dashboardApi.getCurrentInfo().then((res) => {
      state.currentInfo = res.data;
    });
  };

  // 管理者 - 我的项目
  const getMyProjectList = async () => {
    await projectApi.getMyProjectList({ pageNum: 1, pageSize: 7 }).then((res) => {
      state.projectList = res.data;
    });
  };

  // 投资人 - 我的项目
  const getStaredOrg = async () => {
    await dashboardApi.getStaredOrg().then((res) => {
      state.projectList = res.data;
    });
  };

  // 消息列表
  const getMessagesList = async () => {
    await dashboardApi.getMessagesList({ pageNum: 1, pageSize: 4 }).then((res) => {
      state.messagesList = res.data;
    });
  };

  // 右侧边栏 right-side
  // 管理者 - 便捷导航
  const getNavList = async () => {
    await dashboardApi.getNavList().then((res) => {
      state.navList = res.data;
    });
  };

  // 投资人 - 可能感兴趣的项目
  const getInterestedProject = async () => {
    await dashboardApi.getInterestedProject().then((res) => {
      state.interestedProjectList = res.data;
    });
  };

  // 投资人 - 推荐案例
  const getRecommendCase = async () => {
    await dashboardApi.getRecommendCase().then((res) => {
      state.caseList = res.data;
    });
  };

  // 投资人 - 最新经验
  const getExperienceList = async () => {
    await experienceApi.getList({ pageNum: 1, pageSize: 3 }).then((res) => {
      state.experienceList = res.data;
    });
  };

  // 投资人 - 最新政策
  const getPolicyList = async () => {
    await policyApi.getList({ pageNum: 1, pageSize: 3 }).then((res) => {
      state.policyList = res.data;
    });
  };

  // 查看消息
  const viewMessage = (row: any) => {
    state.viewMessageModal = {
      visible: true,
      rowData: row,
    };
  };

  // 回复消息
  const replyMessage = (row: any) => {
    state.replyMessageModal = {
      visible: true,
      rowData: row,
    };
  };

  // init
  React.useEffect(() => {
    getCurrentInfo().then(() => {
      if (state.currentInfo.roleType === 1) {
        // 管理员 1
        getMyProjectList();
        getNavList();
      } else {
        // 投资人 2
        getStaredOrg();

        getInterestedProject();
        getRecommendCase();
        getExperienceList();
        getPolicyList();
      }

      getMessagesList();
    });
  }, []);


  const { currentInfo } = state;

  return (
    <div>
      <Card {...cardConfig} className="card">
        <div className="flex justify-between">
          <div className="flex">
            <Avatar size={60} src={`${config.ossUrl}${currentInfo.headPortrait as string}`} />

            <div className="flex flex-col justify-between ml-4">
              <div className="font-bold text-lg">Welcome，{currentInfo.username}</div>
              <div className="text-xs content-center">
                <span>
                  <span className="text-gray-500 mr-2">Identity:</span>
                  {currentInfo.roleName}
                </span>

                <Link to={
                  currentInfo.orgId
                    ? `/institution/edit?id=${currentInfo.orgId as string}`
                    : '/institution/add'
                } className="link ml-4">Verify Now</Link>

                <Link to={'/dashboard/profile'}>
                  <FormOutlined className="ml-4 align-middle text-gray-500 cursor-pointer text-sm" />
                </Link>
              </div>
            </div>
          </div>

          <div className="flex items-center">
            <div className="flex flex-col h-full items-center justify-between profile-num-wrap">
              <div className="flex text-xs text-gray-500">My Projects</div>
              <div className="profile-number">{currentInfo.myProjectNum || '-'}</div>
            </div>

            <Divider type="vertical" className="profile-divider" />

            <div className="flex flex-col h-full items-center justify-between profile-num-wrap">
              <div className="flex text-xs text-gray-500">In Chat</div>
              <div className="profile-number">{currentInfo.chatNum || '-'}</div>
            </div>
          </div>
        </div>
      </Card>

      <div className="flex flex-row card-wrap">
        <div className="left-side flex flex-col flex-none w-2/3 mr-4">
          {/* 管理者 - 我的项目 My Projects */}
          <Card
            {...cardConfig}
            title={
              setCardTitle(`${state.currentInfo.roleType === 1 ? 'My Projects' : 'Focused Projects'}`)
            }
            extra={
              setCardExtra('Projects', '/project/my')
            }
            className="card"
          >
            {
              state.projectList?.length
                ? state.projectList.map((v: any): JSX.Element => (
                  <Card.Grid className="grid-item cursor-pointer" key={v.id}>
                    <Link className="item-cell" to={`/project/details?id=${v.id as string}`}>
                      <div>
                        <div className="item-title">
                          <span className="title-circle">
                            <FormOutlined className="title-icon" />
                          </span>
                          <span className="title-text">{v.projectTitle}</span>
                        </div>
                        <div className="item-content">{v.content}</div>
                      </div>
                      <div className="flex justify-between text-xs">
                        <span className="w-1/3 truncate text-left">{v.countryName}</span>
                        <span className="w-1/3 truncate text-center">{v.totalAmount}</span>
                        <span className="w-1/3 truncate text-right">{v.industryName}</span>
                      </div>
                    </Link>
                  </Card.Grid>
                )) : null
            }
          </Card>

          {/* Message List */}
          <Card
            {...cardConfig}
            title={
              setCardTitle('Message')
            }
            extra={
              setCardExtra('Messages', '/dashboard/messages')
            }
            className="card card-message"
          >
            {
              // TODO: project, time, operation type
              state.messagesList?.length
                ? state.messagesList.map((v: any): JSX.Element => (
                  <div className="flex justify-between message-wrap" key={v.id}>
                    <div className="flex">
                      <Avatar size={40} src={`${config.ossUrl}ppp/p2414.jpg`} />
                      <div className="flex flex-col justify-between ml-4 message-border">
                        <div>
                          <span className="font-bold">{v.sendName}</span>
                          <span className="ml-2 mr-2 link">consult</span>
                          <span>in</span>
                          <Link
                            className="ml-2 mr-2 link"
                            to={`/project/details?id=${v.id as string}`}
                          >
                            project {v.sendName}
                          </Link>
                        </div>
                        <div className="text-xs content-center text-gray-500 mr-2">3 days ago</div>
                      </div>
                    </div>
                    <div className="flex flex-1 items-center justify-end message-border">
                      <EyeOutlined
                        className="text-xl text-gray-500 cursor-pointer"
                        onClick={() => viewMessage(v)}
                      />
                      <MessageOutlined
                        className="text-base text-gray-500 cursor-pointer ml-6"
                        onClick={() => replyMessage(v)}
                      />
                    </div>
                  </div>
                )) : null
            }
          </Card>
        </div>

        {/* 右侧栏目 right-side */}
        <div className="right-side flex flex-col flex-auto">
          {
            /* 管理者 - 便捷导航 Navigation */
            state.currentInfo.roleType === 1
              ? <Card
                {...cardConfig}
                title={
                  setCardTitle('Navigation')
                }
                className="card"
              >
                {
                  state.navList.map((v: any) => (
                    <Link
                      key={v.id}
                      className="link inline-block mr-4"
                      to={v.url || ''}
                      target="_blank"
                    >
                      {v.name}
                    </Link>
                  ))
                }
              </Card> : null
          }

          {
            // TODO: 管理者 - 项目分布统计 Project Distribution
            state.currentInfo.roleType === 1
              ? <Card
                {...cardConfig}
                title={
                  setCardTitle('Project Distribution')
                }
                className="card"
              >
                <ProjectDistribution />
              </Card> : null
          }

          {
            // TODO: 管理者 - 机构分布统计 Institution Distribution
            state.currentInfo.roleType === 1
              ? <Card
                {...cardConfig}
                title={
                  setCardTitle('Institution Distribution')
                }
                className="card"
              >
                <InstitutionDistribution />
              </Card> : null
          }

          {
            /* 投资人 - 可能感兴趣的项目 Recommended Projects */
            state.interestedProjectList?.length
              ? <Card
                {...cardConfig}
                title={
                  setCardTitle('Recommended Projects')
                }
                className="card"
              >
                {
                  state.interestedProjectList.map((v: any) => (
                    <Link key={v.id} to={`/project/details?id=${v.id as string}`}>
                      <div className="flex justify-between">
                        <span className="w-1/3 truncate pr-2">{v.countryName}</span>
                        <span className="w-1/3 truncate pr-2">{v.projectTitle}</span>
                        <span className="w-1/3 truncate">{v.totalAmount}</span>
                      </div>
                    </Link>
                  ))
                }
              </Card> : null
          }

          {
            /* 投资人 - 推荐案例 Recommended Projects */
            state.caseList?.length
              ? <Card
                {...cardConfig}
                title={
                  setCardTitle('Recommended Cases')
                }
                className="card"
              >
                {
                  state.caseList.map((v: any) => (
                    <Link key={v.id} to={`/case/detail?id=${v.id as string}`}>
                      <div className="flex justify-between">
                        <span className="w-1/3 truncate pr-2">{v.caseName}</span>
                        <span className="w-1/3 truncate pr-2">{v.countryName}</span>
                        <span className="w-1/3 truncate">{moment(v.createTime).format('YYYY/MM/DD')}</span>
                      </div>
                    </Link>
                  ))
                }
              </Card> : null
          }

          {
            /* 投资人 - 最新经验 Lastest Experience */
            state.experienceList?.length
              ? <Card
                {...cardConfig}
                title={
                  setCardTitle('Lastest Experience')
                }
                className="card"
              >
                {
                  state.experienceList.map((v: any) => (
                    <Link key={v.id} to={`/experience/detail?id=${v.id as string}`}>
                      <div className="flex justify-between">
                        <span className="w-1/3 truncate pr-2">{v.expName}</span>
                        <span className="w-1/3 truncate pr-2">{v.countryName}</span>
                        <span className="w-1/3 truncate">{moment(v.createTime).format('YYYY/MM/DD')}</span>
                      </div>
                    </Link>
                  ))
                }
              </Card> : null
          }

          {
            /* 投资人 - 最新政策 Latest Policy */
            state.policyList?.length
              ? <Card
                {...cardConfig}
                title={
                  setCardTitle('Latest Policy')
                }
                className="card"
              >
                {
                  state.policyList.map((v: any) => (
                    <Link key={v.id} to={`/case/policy?id=${v.id as string}`}>
                      <div className="flex justify-between">
                        <span className="w-1/3 truncate pr-2">{v.name}</span>
                        <span className="w-1/3 truncate pr-2">{v.countryName}</span>
                        <span className="w-1/3 truncate">{moment(v.createTime).format('YYYY/MM/DD')}</span>
                      </div>
                    </Link>
                  ))
                }
              </Card> : null
          }
        </div>
      </div>

      {
        state.viewMessageModal.visible
        && <ViewMessageModal
          state={state.viewMessageModal}
          rowData={state.viewMessageModal.rowData}
          replyModal={state.replyMessageModal}
        />
      }

      {
        state.replyMessageModal.visible
        && <ReplyMessageModal
          state={state.replyMessageModal}
          rowData={state.replyMessageModal.rowData}
        />
      }

    </div>
  );
});

export default DashboardPage;
